<template>
  <el-upload
    :disabled="props.editDisables?.includes(filed.field)"
    style="width: 400px"
    :list-type="filed.type.value.includes('image') ? 'picture' : 'text'"
    v-model:file-list="fileList[filed.field]"
    :action="uploadUrl"
    :headers="{ token }"
    :multiple="filed.type.upload.num > 1 ? true : false"
    :on-preview="filePreview"
    :on-remove="fileRemove"
    :limit="filed.type.upload.num"
    :on-exceed="fileExceed"
    :before-upload="beforeUpload"
    :on-success="successUpload"
  >
    <el-button type="primary" @click="uploadSetting = filed">上传</el-button>
    <template #tip>
      <div class="el-upload__tip">
        类型限制
        <span style="font-weight: bold">{{ filed.type.upload.type.join('/') }}</span>
        大小限制
        <span style="font-weight: bold">{{ filed.type.upload.size }} KB</span>
        数量限制
        <span style="font-weight: bold">{{ filed.type.upload.num }}</span>
      </div>
    </template>
  </el-upload>
</template>
<script setup>
import { compress } from '@/utils/fileUtils'
import { ElMessage } from 'element-plus'
import { ref, inject } from 'vue'
const token = sessionStorage.getItem('token')
const uploadUrl = inject('uploadUrl')
const filed = defineModel('filed')
const fileList = defineModel('fileList')
const props = defineProps(['editDisables'])
const uploadSetting = ref({})
// 文件预览
function filePreview(uploadFile) {
  window.open(uploadFile.response.data.url, '_blank')
}
// 文件删除
function fileRemove(file, uploadFiles) {
  console.log('文件删除', file, uploadFiles)
}
// 文件超出限制
function fileExceed(files, uploadFiles) {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  )
}
// 文件上传检查
function beforeUpload(file) {
  const sizeKb = (file.size / 1024).toFixed(2)
  if (sizeKb > uploadSetting.value.type.upload.size) {
    // 判断是否自动压缩
    if (uploadSetting.value.type.upload.compress) {
      return compress(file, uploadSetting.value.type.upload.size)
    }
    ElMessage.warning(
      `上传的文件 ${sizeKb}/KB 超出文件大小限制 ${uploadSetting.value.type.upload.size}/KB`
    )
    return false
  }
  const fileType = file.name.split('.').pop().toLowerCase()
  if (!uploadSetting.value.type.upload.type.includes(fileType)) {
    ElMessage.warning(`不允许上传的文件类型 ${fileType}`)
    return false
  }
}
// 文件上传成功
function successUpload(response, uploadFile, uploadFiles) {
  console.log(response, uploadFile, uploadFiles)
}
</script>
<style scoped></style>
